package com.java.base.exercise.current;

import java.util.HashSet;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author RenPu
 * @Date 2022/2/15 17:18
 * @Version 1.0
 * @Description: 基于自定义AQS,实现自定义CountDownLatch (计数器)
 **/
public class CDLDdemo {

    AQSdemo aqSdemo =new AQSdemo(){

        //辅助CountDownLatch的await的操作，将线程放入到等待线程容器
        @Override
        public int tryAcquireShared() {
            return aqSdemo.getState().get()==0?1:-1;
        }

        //辅助CountDownLatch的数值递减的操作
        @Override
        public boolean tryReleaseShared() {
            return aqSdemo.getState().decrementAndGet()==0;
        }
    };


    public CDLDdemo() {
    }

    //计数器数量的设置
    public CDLDdemo(int count) {
        aqSdemo.setState(new AtomicInteger(count));
    }

    public void await(){
      aqSdemo.acquireShared();

    }

   public void countDown(){
     aqSdemo.releaseShared();
   }


    public static void main(String[] args) {
        CDLDdemo cdLdemo = new CDLDdemo(10); // 创建，计数数值
        for (int i = 0; i < 10; i++) { // 启动九个线程，最后一个两秒后启动
            int finalI = i;
            new Thread(() -> {
                try {
                    Thread.sleep(2000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("我是" + Thread.currentThread() + ".我执行接口-" + finalI +"调用了");
                cdLdemo.countDown(); // 参与计数
                // 不影响后续操作
            }).start();
        }

        cdLdemo.await(); // 等待计数器为0
        System.out.println("全部执行完毕.我来召唤神龙");

    }



    }



